/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import business.GUIMemento.MementoTextChanges;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import models.TextChanges;

/**
 *
 * @author Jordab
 */
public class TextChangeListener implements DocumentListener {

    private final StringBuilder textBackup;
    private final MementoTextChanges mtc;

    public TextChangeListener() {
        textBackup = new StringBuilder();
        mtc = MementoTextChanges.getInstance(textBackup);
    }

    @Override
    public void insertUpdate(DocumentEvent de) {
        if (!mtc.getChangeFromMemento()) {
            try {
                TextChanges tc = new TextChanges(de.getDocument().getText(de.getOffset(), de.getLength()), de.getOffset(), de.getLength(), true);
                textBackup.insert(tc.getOffset(), tc.getText()); //texto de backup(para quando precisar apagar)
                mtc.pushAndSend(tc); //enviando ao memento                        
                System.out.println(textBackup.substring(0));
            } catch (StringIndexOutOfBoundsException | BadLocationException ex) {
                System.out.println("ERROR ON INSERT" + ex.getLocalizedMessage());
            }
        }
    }

    @Override
    public void removeUpdate(DocumentEvent de) {
        if (!mtc.getChangeFromMemento()) {
            try {
                TextChanges tc = new TextChanges(textBackup.substring(de.getOffset(), de.getOffset() + de.getLength()), de.getOffset(), de.getLength(), false); //pega texto do backup
                textBackup.delete(tc.getOffset(), tc.getOffset() + de.getLength()); //backup 
                mtc.pushAndSend(tc); //enviando ao memento
                System.out.println(textBackup.substring(0));
            } catch (StringIndexOutOfBoundsException ex) {
                System.out.println("ERROR ON DELETE " + ex.getLocalizedMessage());
            }
        }
    }

    @Override
    public void changedUpdate(DocumentEvent de) {
        System.out.println("UPDATE");
    }

}
